<template>
  <view class="weather" @click="onPopupRecord">
    <view class="weather-left">
      <view class="weather-time">{{ dateTime }}</view>
      <view class="weather-date">{{ dateDay }}</view>
    </view>
    <view class="weather-right">
      <view class="weather-temp">
        柜机当前温度：<text
          :style="{
            color:
              cabinetInfo?.temperatureMin >= tempNum ||
              cabinetInfo?.temperatureMax <= tempNum
                ? '#FF0000'
                : '#41992d',
          }"
          >{{ tempNum }}℃</text
        >
      </view>
      <view class="weather-humidity">
        柜机当前湿度：<text
          :style="{
            color:
              cabinetInfo?.humidityMin >= humiNum || cabinetInfo?.humidityMax <= humiNum
                ? '#FF0000'
                : '#41992d',
          }"
          >{{ humiNum }}%RH</text
        >
      </view>
    </view>
    <Weather-popup v-model="popupShow" />
  </view>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { timeFormat } from "@/request/common";
import WeatherPopup from "./WeatherPopup.vue";
// #ifdef APP-PLUS
const port = uni.requireNativePlugin("hpb-serialport"); // 温湿度传感器
// #endif

const dateDay = ref<any>(""); // 当前日期
const dateTime = ref<any>(""); // 当前时间
const timer = ref<any>(null); // 定时器
const totalNumber = ref<any>(0); // 统计总数
const sendNum = ref<any>(0); // 发送状态
const tempNum = ref<any>("-"); // 温度
const humiNum = ref<any>("-"); // 湿度
const clickNumber = ref<number>(0); // 点击次数
const clickTimer = ref<any>(null); // 点击定时器
const popupShow = ref<boolean>(false); // 设置弹窗
const cabinetInfo = ref<any>({}); // 柜机信息

onMounted(() => {
  // #ifdef APP-PLUS
  createProt();
  // #endif
  getDay();
  timer.value = setInterval(() => {
    cabinetInfo.value = uni.getStorageSync("cabinet");
    getDay();
    totalNumber.value++;
    if (totalNumber.value > 10 * 60) {
      totalNumber.value = 0;
      uni.$emit("heart", {
        temperature: tempNum.value == "-" ? "" : tempNum.value,
        humidity: humiNum.value == "-" ? "" : humiNum.value,
        sensorStatus: tempNum.value == "-" ? 0 : 1,
      });
    }
    // #ifdef APP-PLUS
    getRealInfo();
    // #endif
  }, 1000);
});

onLoad(() => {
  uni.$on("HEARTBEAT", () => {
    totalNumber.value = 0;
    uni.$emit("heart", {
      temperature: tempNum.value == "-" ? "" : tempNum.value,
      humidity: humiNum.value == "-" ? "" : humiNum.value,
      sensorStatus: tempNum.value == "-" ? 0 : 1,
    });
  });
});

// 获取串口信息
const createProt = async () => {
  let config = {
    path: "/dev/ttyUSB11", // 串口地址
    baudRate: 9600, // 波特率
    stopBit: 1, //停止位
    dataBits: 8, // 数据位
    parity: 0, // 校验位
  };
  port.open(config, (res: any) => {
    if (res.status) {
      port.addListenerAndKeepAlive((obj: any) => {
        sendNum.value = 0;
        let temp = toHexByte(obj.bytes[3]) + toHexByte(obj.bytes[4]); // 温度
        let humi = toHexByte(obj.bytes[5]) + toHexByte(obj.bytes[6]); // 湿度
        tempNum.value = parseInt(temp, 16) / 10;
        humiNum.value = parseInt(humi, 16) / 10;
      });
    } else {
      console.log("温湿度传感器：", res.msg);
    }
  });
};

// 进制转换
const toHexByte = (num: any) => {
  return ((num & 0xff) + 0x100).toString(16).substr(-2).toUpperCase();
};

/**
 * 获取实时数据
 * 获取温湿度 01040000000271CB
 * 获取温度   01040000000131CA
 * 获取湿度   010400010001600A
 * 设置地址   01060064000249D4
 */
const getRealInfo = () => {
  port.send(
    {
      sends: ["01040000000271CB", "", ""],
    },
    (res: any) => {
      sendNum.value++;
      if (sendNum.value > 5) {
        sendNum.value = 0;
        tempNum.value = "-";
        humiNum.value = "-";
        handleConnect();
      }
    }
  );
};

// 获取当前时间
const getDay = () => {
  let date = new Date();
  dateDay.value = timeFormat(date, "yyyy / mm / dd");
  dateTime.value = timeFormat(date, "hh:MM");
};

// 重连
const handleConnect = () => {
  port.getStatus((res: any) => {
    if (res.status) {
      port.close();
    }
    createProt();
  });
};

// 打开设置弹窗
const onPopupRecord = () => {
  clickNumber.value++;
  if (clickNumber.value >= 10) {
    let serial = uni.getStorageSync("serialNumber"); // 获取序列号
    if (serial) {
      popupShow.value = true;
      clickNumber.value = 0;
    } else {
      uni.showToast({
        title: "请先绑定柜机",
        icon: "none",
      });
      clickNumber.value = 0;
    }
  }
  if (clickTimer.value) {
    clearTimeout(clickTimer.value);
  }
  clickTimer.value = setTimeout(() => {
    clickNumber.value = 0;
    clearTimeout(clickTimer.value);
    clickTimer.value = null;
  }, 1000);
};

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  if (clickTimer.value) {
    clearTimeout(clickTimer.value);
    clickTimer.value = null;
  }
  // #ifdef APP-PLUS
  port.getStatus((res: any) => {
    if (res.status) {
      port.close();
    }
  });
  // #endif
});
</script>
<style lang="scss" scoped>
.weather {
  display: flex;
  align-items: center;
  background: url("../../static/weather.png") no-repeat;
  background-size: 100% 100%;
  border-radius: 6.95rpx;
  padding: 60rpx 100rpx 76rpx 100rpx;
  height: 240rpx;
  border-radius: 25.02rpx;
  box-sizing: border-box;
  .weather-left {
    width: 40%;
    border-right: 1px solid #fff;
    font-family: Source Han Sans;
    .weather-date {
      line-height: 29.9rpx;
      color: #3d3d3d;
      font-weight: 400;
      font-size: 20.85rpx;
    }
    .weather-time {
      color: #41992d;
      font-size: 50.04rpx;
      font-weight: 700;
      line-height: 62.55rpx;
    }
  }
  .weather-right {
    width: 60%;
    height: 100%;
    font-family: Source Han Sans;
    font-size: 20.85rpx;
    color: #3d3d3d;
    padding-left: 43.09rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .weather-temp {
      line-height: 48.65rpx;
      text {
        font-weight: 700;
      }
    }
    .weather-humidity {
      line-height: 48.65rpx;
      text {
        font-weight: 700;
      }
    }
  }
}
</style>
